<template>
  <div>
    <!-- 设置协议价 -->
    <a-modal
      v-model:open="visible"
      width="1000px"
      title="协议价设置"
      :footer="null"
      :maskClosable="false"
    >
      <div v-global-loading="modalloading">
        <a-form :model="statetable" ref="formRef" :labelCol="{span: 8}">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="是否指定全商品">
                <a-radio-group
                  v-model:value="statetable.isAllProduct"
                  name="isAllProduct"
                >
                  <a-radio :value="true">是</a-radio>
                  <a-radio :value="false">否</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item
                label="协议价折扣"
                v-if="statetable.isDiscount && statetable.isAllProduct"
              >
                <a-input-number
                  style="width: 240px"
                  min="0"
                  v-model:value="statetable.discount"
                  :controls="false"
                  addon-after="%"
                />
              </a-form-item>
              <a-form-item
                label="协议价固定金额"
                v-if="!statetable.isDiscount && statetable.isAllProduct"
              >
                <a-input-number
                  style="width: 240px"
                  min="0"
                  v-model:value="statetable.discount"
                  :controls="false"
                  addon-after="元"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="计算方式" v-if="statetable.isAllProduct">
                <a-radio-group
                  v-model:value="statetable.isDiscount"
                  name="isDiscount"
                  @change="
                    () => {
                      statetable.discount = 0;
                    }
                  "
                >
                  <a-radio :value="true">折扣</a-radio>
                  <a-radio :value="false">固定价</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="选择商品" v-if="!statetable.isAllProduct">
                <span class="pointer c-primaryColor" @click="selectGoods"
                  >点击选择</span
                >
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div v-if="!statetable.isAllProduct">
          <div style="font-size: 16px; font-weight: 800">已选择的商品：</div>
          <a-table
            size="small"
            :dataSource="statetable.productInfoDtos"
            :columns="columns1"
            bordered
            :pagination="false"
          >
            <template #bodyCell="{text, record, index, column}">
              <template v-if="column.title == '产品图片'">
                <div
                  class="pointer"
                  v-if="
                    record.detailUrls &&
                    record.detailUrls.length &&
                    record.detailUrls[0].ImgUrl
                  "
                  @click="
                    () => {
                      setVisible(true, index);
                    }
                  "
                >
                  <img
                    :src="record.detailUrls[0].ImgUrl"
                    alt=""
                    style="height: 30px"
                  />
                  <a-image
                    :width="0"
                    :style="{display: 'none'}"
                    :preview="{
                      visible: visibleImg[index],
                      onVisibleChange: (e) => {
                        setVisible(e, index);
                      }
                    }"
                    :src="record.detailUrls[0].ImgUrl"
                  />
                </div>
              </template>
              <template v-if="column.title == '计算方式'">
                <a-select
                  v-model:value="statetable.productInfoDtos[index].isDiscount"
                  style="width: 130px"
                  @change="
                    () => {
                      statetable.productInfoDtos[index].discount = 0;
                    }
                  "
                >
                  <a-select-option :value="true">折扣</a-select-option>
                  <a-select-option :value="false">固定价</a-select-option>
                </a-select>
              </template>
              <template v-if="column.title == '协议价'">
                <a-input-number
                  v-if="statetable.productInfoDtos[index].isDiscount"
                  min="0"
                  v-model:value="statetable.productInfoDtos[index].discount"
                  style="width: 130px"
                  :controls="false"
                  addon-after="%"
                ></a-input-number>
                <a-input-number
                  v-else
                  v-model:value="statetable.productInfoDtos[index].discount"
                  min="0"
                  style="width: 130px"
                  :controls="false"
                  addon-after="元"
                ></a-input-number>
              </template>
              <template v-if="column.title == '操作'">
                <span
                  class="pointer"
                  style="color: red"
                  @click="deleDiscount(index)"
                  >删除</span
                >
              </template>
            </template>
          </a-table>
        </div>
        <div style="display: flex; justify-content: end; margin-top: 10px">
          <a-button style="margin-right: 14px" @click="addFormData(1)"
            >取消</a-button
          >
          <a-button type="primary" @click="addFormData(2)">确定</a-button>
        </div>
      </div>
    </a-modal>
    <!-- 选择商品 -->
    <a-modal
      v-model:open="visible1"
      width="800px"
      title="选择商品"
      :footer="null"
      :maskClosable="false"
    >
      <div style="display: flex; justify-content: end; margin-bottom: 10px">
        <a-input-search
          allowClear
          v-model:value="pageSet.productName"
          placeholder="请输入商品名称"
          enter-button
          @search="loadPagination(true)"
          style="width: 300px"
        />
      </div>
      <a-table
        size="small"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        bordered
        :pagination="false"
        row-key="id"
        :row-selection="{
          selectedRowKeys: selectedRowKeysList,
          onChange: onSelectChange,
          preserveSelectedRowKeys: true
        }"
        :scroll="{x: 700, y: 500}"
      >
        <template #bodyCell="{text, record, index, column}">
          <template v-if="column.title == '产品图片'">
            <div
              class="pointer"
              v-if="
                record.detailUrls &&
                record.detailUrls.length &&
                record.detailUrls[0].ImgUrl
              "
              @click="
                () => {
                  setVisible1(true, index);
                }
              "
            >
              <img
                :src="record.detailUrls[0].ImgUrl"
                alt=""
                style="height: 30px"
              />
              <a-image
                :width="0"
                :style="{display: 'none'}"
                :preview="{
                  visible: visibleImg1[index],
                  onVisibleChange: (e) => {
                    setVisible1(e, index);
                  }
                }"
                :src="record.detailUrls[0].ImgUrl"
              />
            </div>
          </template>
        </template>
      </a-table>
      <Pagination
        :pageSet="pageSet"
        style="margin-top: 10px"
        :loadPagination="loadPagination"
      ></Pagination>
      <div style="display: flex; justify-content: end">
        <a-button type="primary" @click="visible1 = false">确定</a-button>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import {ref, computed} from "vue";
import {productInfoPage} from "@/api/merchandise/commodity";
import Pagination from "@/components/pagination/Pagination.vue";
import {message, Modal} from "ant-design-vue";
import {membersInfoUpdateDiscount} from "@/api/customerArchives/memberManagement";
const deleDiscount = (index) => {
  Modal.confirm({
    title: "提示",
    content: "确定要删除该商品吗？",
    onOk() {
      statetable.value.productInfoDtos.splice(index, 1);
    }
  });
};
const setVisible = (flag, index) => {
  visibleImg.value[index] = flag;
};
const visibleImg = ref<any>([]);
const setVisible1 = (flag, index) => {
  visibleImg1.value[index] = flag;
};
const visibleImg1 = ref<any>([]);
const visible = ref<boolean>(false);
const visible1 = ref<boolean>(false);
const modalloading = ref<boolean>(false);
const tableData = ref<Array<any>>([]);
const tableLoading = ref<boolean>(false);
const props = defineProps({
  data: {
    type: Object,
    default: {}
  }
});
const emits = defineEmits(["update:list", "ok", "update:data"]);
//当前已经选择的ID集合
const selectedRowKeysList: any = ref([]);
//返回值
const statetable = computed({
  get() {
    selectedRowKeysList.value = [];
    if (
      Array.isArray(props.data.productInfoDtos) &&
      props.data.productInfoDtos.length > 0
    ) {
      props.data.productInfoDtos.forEach((item) => {
        selectedRowKeysList.value.push(item.id);
        if (item.detailUrls) {
          if (typeof item.detailUrls == "string") {
            item.detailUrls = JSON.parse(item.detailUrls) || [];
          } else {
            item.detailUrls = item.detailUrls || [];
          }
        } else {
          item.detailUrls = [];
        }
      });
    }
    return props.data;
  },
  set(value) {
    emits("update:data", value);
  }
});
function onSelectChange(selectedRowKeys, data) {
  let list: any = []; //初次过滤被删除的元素
  statetable.value.productInfoDtos.forEach((item) => {
    if (selectedRowKeys.includes(item.id)) {
      list.push(item);
    }
  });
  let list1: any = []; //添加的新元素
  data.forEach((item) => {
    let flag = true; //默认是新的
    if (item) {
      statetable.value.productInfoDtos.forEach((v) => {
        if (v.id == item.id) {
          //当ID 相同 不是新数据不新加
          flag = false;
        }
      });
    } else {
      flag = false;
    }
    if (flag) {
      list1.push(item);
    }
  });
  list.push(...list1);
  list.forEach((item) => {
    item.isDiscount =
      typeof item.isDiscount == "boolean" ? item.isDiscount : true;
    item.discount = item.discount ? item.discount : 0;
  });
  statetable.value.productInfoDtos = list;
  selectedRowKeysList.value = selectedRowKeys;
}
const columns = ref<Array<any>>([
  {
    title: "序号",
    dataIndex: "index",
    align: "center",
    width: 50,
    customRender: ({index}) => {
      return index + 1;
    },
    fixed: "left"
  },
  {
    title: "产品名称",
    dataIndex: "productName",
    align: "center",
    width: 200
  },
  {
    title: "产品图片",
    dataIndex: "detailUrls",
    align: "center",
    width: 200
  },
  {
    title: "产品编码",
    dataIndex: "productCode",
    align: "center",
    width: 120
  }
]);
const columns1 = ref<Array<any>>([
  {
    title: "序号",
    dataIndex: "index",
    align: "center",
    width: 50,
    customRender: ({index}) => {
      return index + 1;
    },
    fixed: "left"
  },
  {
    title: "产品名称",
    dataIndex: "productName",
    align: "center",
    width: 200
  },
  {
    title: "产品图片",
    dataIndex: "detailUrls",
    align: "center",
    width: 200
  },
  {
    title: "产品编码",
    dataIndex: "productCode",
    align: "center",
    width: 120
  },
  {
    title: "计算方式",
    dataIndex: "isDiscount",
    align: "center",
    width: 160
  },
  {
    title: "协议价",
    dataIndex: "discount",
    align: "center",
    width: 160
  },
  {
    title: "操作",
    dataIndex: "dele",
    align: "center",
    width: 120
  }
]);
const addFormData = (type: number) => {
  if (type == 1) {
    visible.value = false;
  } else {
    statetable.value.discount = statetable.value.discount
      ? statetable.value.discount
      : 0;
    const formData = ref<any>({
      id: statetable.value.id,
      discount: statetable.value.discount,
      isDiscount: statetable.value.isDiscount,
      isAllProduct: statetable.value.isAllProduct,
      products: []
    });
    statetable.value.productInfoDtos.forEach((item) => {
      item.discount = item.discount ? item.discount : 0;
      let obj = {
        productId: item.id,
        isDiscount: item.isDiscount,
        discount: item.discount
      };
      formData.value.products.push(obj);
    });
    if (formData.value.isAllProduct) {
      //全商品
      if (formData.value.discount == 0) {
        Modal.confirm({
          title: "提示",
          content: "当前协议价折扣或固定金额为0，确认要提交吗？",
          onOk() {
            modalloading.value = true;
            membersInfoUpdateDiscount(formData.value)
              .then(() => {
                message.success("设置成功");
                visible.value = false;
              })
              .finally(() => {
                modalloading.value = false;
              });
          }
        });
      } else {
        modalloading.value = true;
        membersInfoUpdateDiscount(formData.value)
          .then(() => {
            message.success("设置成功");
            visible.value = false;
          })
          .finally(() => {
            modalloading.value = false;
          });
      }
    } else {
      //部分商品
      let flag = true;
      formData.value.products.forEach((item) => {
        if (!item.discount) {
          flag = false;
        }
      });
      if (flag) {
        modalloading.value = true;
        membersInfoUpdateDiscount(formData.value)
          .then(() => {
            message.success("设置成功");
            visible.value = false;
          })
          .finally(() => {
            modalloading.value = false;
          });
      } else {
        Modal.confirm({
          title: "提示",
          content: "选中商品有协议价折扣或固定金额为0，确认要提交吗？",
          onOk() {
            modalloading.value = true;
            membersInfoUpdateDiscount(formData.value)
              .then(() => {
                message.success("设置成功");
                visible.value = false;
              })
              .finally(() => {
                modalloading.value = false;
              });
          }
        });
      }
    }
  }
};
const pageSet = ref<any>({
  pageNo: 1,
  pageSize: 20,
  total: 0,
  publishStatus: 1
});
const loadPagination = (flag: boolean = false): void => {
  if (flag) {
    pageSet.value.pageNo = 1;
  }
  tableLoading.value = true;
  productInfoPage(pageSet.value)
    .then((res) => {
      tableData.value = res.data.rows;
      tableData.value.forEach((item) => {
        if (item.detailUrls) {
          item.detailUrls = JSON.parse(item.detailUrls) || [];
        } else {
          item.detailUrls = [];
        }
      });
      pageSet.value.total = res.data.totalRows;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
const showModal = () => {
  visible.value = true;
};
//选择商品
const selectGoods = () => {
  pageSet.value = {
    pageNo: 1,
    pageSize: 20,
    total: 0,
    publishStatus: 1
  };
  visible1.value = true;
  loadPagination(true);
};
const nodeModal = () => {
  visible.value = false;
};
defineExpose({
  showModal,
  nodeModal,
  modalloading
});
</script>
<style lang="less" scoped></style>
